<template>
  <template v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef">
      <FormItem name="principalUserName" class="enter-x">
        <Input size="large" v-model:value="formData.principalUserName" :placeholder="t('sys.login.principalUserName')" class="fix-auto-fill" />
      </FormItem>

      <FormItem name="agentUserName" class="enter-x">
        <Input size="large" v-model:value="formData.agentUserName" :placeholder="t('sys.login.agentUserName')" class="fix-auto-fill" />
      </FormItem>

      <FormItem name="agentPassword" class="enter-x">
        <InputPassword size="large" visibilityToggle v-model:value="formData.agentPassword" :placeholder="t('sys.login.password')" />
      </FormItem>

      <!--验证码-->
      <ARow class="enter-x">
        <ACol :span="12">
          <FormItem name="inputCode" class="enter-x">
            <Input size="large" v-model:value="formData.inputCode" :placeholder="t('sys.login.inputCode')" style="min-width: 100px" />
          </FormItem>
        </ACol>
        <ACol :span="8">
          <FormItem :style="{ 'text-align': 'right', 'margin-left': '20px' }" class="enter-x">
            <img
              v-if="randCodeData.requestCodeSuccess"
              style="margin-top: 2px; max-width: initial"
              :src="randCodeData.randCodeImage"
              @click="handleChangeCheckCode"
            />
            <img v-else style="margin-top: 2px; max-width: initial" src="../../../assets/images/checkcode.png" @click="handleChangeCheckCode" />
          </FormItem>
        </ACol>
      </ARow>

      <FormItem class="enter-x">
        <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
          {{ t('sys.login.loginButton') }}
        </Button>
        <Button size="large" block class="mt-4" @click="handleBackLogin">
          {{ t('sys.login.backSignIn') }}
        </Button>
      </FormItem>
    </Form>
  </template>
</template>
<script lang="ts" setup>
  import { reactive, ref, computed, unref, toRaw, onMounted } from 'vue';
  import { Form, Input, Button } from 'ant-design-vue';
  import { CountdownInput } from '/@/components/CountDown';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useLoginState, useFormRules, useFormValid, LoginStateEnum, SmsEnum } from './useLogin';
  import { useUserStore } from '/@/store/modules/user';
  import { getCodeInfo } from '/@/api/sys/user';
  import { CryptoUtils } from '/@/utils/encryption/cryptoUtils';
  import { buildUUID } from '/@/utils/uuid';
  import { any } from 'vue-types';

  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { handleBackLogin, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();
  const { notification, createErrorModal } = useMessage();
  const userStore = useUserStore();
  const formRef = ref();
  const loading = ref(false);
  const formData = reactive({
    principalUserName: '',
    agentUserName: '',
    agentPassword: '',
    inputCode: '',
  });
  const randCodeData = reactive({
    randCodeImage: '',
    requestCodeSuccess: false,
    checkKey: '' as any,
  });
  const { validForm } = useFormValid(formRef);
  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.AGENT);
  /**
   * 登录
   */
  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      const cryptoUtils = new CryptoUtils();
      let encryptPrincipalUserName = cryptoUtils.encrypt(data.principalUserName);
      let encryptAgentUserName = cryptoUtils.encrypt(data.agentUserName);
      let encryptPassword = cryptoUtils.encrypt(data.agentPassword);
      const userInfo = await userStore.login(
        toRaw({
          principalUserName: encryptPrincipalUserName,
          agentUserName: encryptAgentUserName,
          agentPassword: encryptPassword,
          decrypt_param: 'principalUserName;agentUserName;agentPassword',
          deviceId: randCodeData.checkKey,
          validCode: data.inputCode,
          grant_type: 'user_agent',
          mode: 'none', //不要默认的错误提示
        })
      );
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realname}`,
          duration: 3,
        });
      }
    } catch (error) {
      const status: string = error?.response?.status ?? '';
      const datamsg: string = error?.response?.data?.msg ?? '';
      let errMessage = '';
      if (status == '400' && datamsg) {
        errMessage = datamsg;
      } else {
        errMessage = error.message;
      }
      notification.error({
        message: t('sys.api.errorTip'),
        description: errMessage || t('sys.api.networkExceptionMsg'),
        duration: 3,
      });
    } finally {
      loading.value = false;
    }
    handleChangeCheckCode();
  }

  function handleChangeCheckCode() {
    formData.inputCode = '';
    randCodeData.checkKey = buildUUID();
    getCodeInfo(randCodeData.checkKey).then((res) => {
      randCodeData.randCodeImage = res;
      randCodeData.requestCodeSuccess = true;
    });
  }

  //初始化验证码
  onMounted(() => {
    handleChangeCheckCode();
  });
</script>
